package com.iot.service.mqtt.handler;

import com.iot.service.mqtt.config.Constant;
import com.iot.service.mqtt.model.fix.TlMqttFixedHead;
import com.iot.service.mqtt.model.payload.TlMqttPublishPayload;
import com.iot.service.mqtt.model.request.TlMqttPubCompReq;
import com.iot.service.mqtt.model.request.TlMqttPubRelReq;
import com.iot.service.mqtt.model.request.TlMqttPublishReq;
import com.iot.service.mqtt.model.variable.TlMqttPubRelVariableHead;
import com.iot.service.mqtt.service.pub.IPublishStoreService;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.mqtt.MqttQoS;
import io.netty.util.AttributeKey;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;


/**
 * @Author: hszhou
 * @Date: 2024/12/5 9:46
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@ChannelHandler.Sharable
@Component
@RequiredArgsConstructor
public class TlMqttPubRelHandler extends SimpleChannelInboundHandler<TlMqttPubRelReq> {

    private static final Logger logger = LoggerFactory.getLogger(TlMqttPubRelHandler.class);


    private final IPublishStoreService publishStoreService;

    private final TlForwardMessageService forwardMessageService;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TlMqttPubRelReq req) throws Exception {
        logger.debug("in【PUBREL】 handler");

        //根据这个消息获取到对应的
        TlMqttPubRelVariableHead variableHead = req.getVariableHead();
        Long messageId = variableHead.getMessageId();
        logger.debug("【BROKER】 2. receive rel messageId is 【{}】",messageId);

        //表示已经收到过这个消息了 可以移除掉这个消息ID了
        logger.debug("【BROKER】 3. remove pub messageId is 【{}】",messageId);

        Object clientIdObj = ctx.channel().attr(AttributeKey.valueOf(Constant.CLIENT_ID)).get();
        logger.debug("收到客户端【{}】的rel消息【{}】",clientIdObj.toString(),messageId);

        TlMqttPublishReq publishReq =(TlMqttPublishReq) ctx.channel().attr(AttributeKey.valueOf(Constant.PUB_MSG)).getAndSet(null);
        //向客户端发送comp消息
        sendComp(messageId,ctx);
        //转发消息给其他客户端
        TlMqttFixedHead fixedHead = publishReq.getFixedHead();
        TlMqttPublishPayload payload = publishReq.getPayload();
        MqttQoS messageQos = fixedHead.getQos();
        String topic = publishReq.getVariableHead().getTopic();
        String content = payload.getContent().toString();
        forwardMessageService.forwardMessage(topic,messageQos,content);


    }

    /**
     * 发送comp消息给客户端 表示broker已经收到了消息
     * @param messageId 消息ID
     * @param ctx 通道
     */
    private void sendComp(Long messageId,ChannelHandlerContext ctx){

        TlMqttPubCompReq res = TlMqttPubCompReq.build(messageId);
        ctx.channel().writeAndFlush(res);
    }


}
